package com.zhj.test;

import com.zhj.bean.Stock;
import com.zhj.lock.RedisLock;
import com.zhj.lock.ZKLock;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.config.Config;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.annotation.Resource;

/**
 * @author zhj
 */
public class stockMain {

    // private static Lock lock = new ReentrantLock();
    // 分布式锁
    @Resource
    private static RedisLock redisLock;
    // private static DBLock dbLock;
    private static RLock rLock;
    private static ZKLock zkLock;

    static {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        // dbLock = classPathXmlApplicationContext.getBean(DBLock.class);
        redisLock = classPathXmlApplicationContext.getBean(RedisLock.class);
        Config config = new Config();
        config.useSingleServer().setAddress("redis://zhj.com:6379").setDatabase(1);
        Redisson redisson = (Redisson) Redisson.create(config);
        rLock = redisson.getLock("redis_lock_stock");
        zkLock = new ZKLock("zhj.com:2181","zk_lock_stock");
    }

    static class StockTask implements Runnable {

        @Override
        public void run() {

            // dbLock.lock();
            // redisLock.lock();
            // rLock.lock();
            zkLock.lock();

            boolean b = new Stock().reduceStock();

            // dbLock.unlock();
            // redisLock.unlock();
            // rLock.unlock();
            zkLock.unlock();
            if (b) {
                System.out.println(Thread.currentThread().getName() + " 减少库存成功");
            } else {
                System.out.println(Thread.currentThread().getName() + " 减少库存失败");
            }
        }
    }

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            new Thread(new StockTask(),"线程" + i).start();
        }
    }
}
